﻿@using BlazorMonaco.Editor
@using FormBuilder.Components
@using FormBuilder.Components.Form
@using FormBuilder.Factories
@using FormBuilder.Models
@using Radzen.Blazor
@using System.Text.Json
@using System.Text.Json.Nodes
@inject IFakerDataServiceFactory fakerDataServiceFactory

<RadzenSteps>
    <Steps>        
        <RadzenStepsItem Text="Input data (JSON)">            
            <StandaloneCodeEditor @ref=editor OnDidInit="HandleOnDidInit" OnDidChangeModelContent="HandleOnEditorContentChanged" ConstructionOptions="EditorConstructionOptions" CssClass="jsonEditor" />
        </RadzenStepsItem>
        <RadzenStepsItem Text="Viewer" Disabled="@(input == null)">
            <FormViewer Context=@debuggingWorkflowContext IsEditModeEnabled="false"></FormViewer>
        </RadzenStepsItem>
    </Steps>
</RadzenSteps>

@code {
    private StandaloneCodeEditor editor;
    [Parameter] public WorkflowContext Context { get; set; }
    private WorkflowContext debuggingWorkflowContext { get; set; }
    JsonObject input { get; set; }

    private async Task HandleOnDidInit()
    {
        await GenerateFakeData();
    }

    private async Task GenerateFakeData()
    {
        if (Context == null || !Context.Definition.Workflow.Steps.Any()) return;
        var firstStep = Context.GetFirstStep();
        if (firstStep == null) return;
        var stepRecord = Context.Definition.Records.Single(r => r.CorrelationId == firstStep.FormRecordCorrelationId);
        var serialized = await fakerDataServiceFactory.Generate(stepRecord.CorrelationId);
        var json = JsonSerializer.Serialize(JsonObject.Parse(serialized), new JsonSerializerOptions { WriteIndented = true });
        debuggingWorkflowContext = Context.BuildNewContextAndMoveToFirstStep(JsonObject.Parse(json).AsObject());
        await editor.SetValue(json);
    }

    private async Task HandleOnEditorContentChanged()
    {
        var value = await editor.GetValue();
        try
        {
            input = JsonObject.Parse(value).AsObject();
        }
        catch
        {
            input = null;
        }
    }

    private StandaloneEditorConstructionOptions EditorConstructionOptions(StandaloneCodeEditor editor)
    {
        return new StandaloneEditorConstructionOptions
        {
            AutomaticLayout = true,
            Language = "json",
            Value = "{}"
        };
    }
}